# -*- coding: utf-8 -*-
"""
@Time : 2024/10/17 18:03
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : get_newest_consume_coupon.py
@Desc : 从Baidu获取最新的消费券信息
"""
import time
import urllib.parse
import requests
from bs4 import BeautifulSoup
import logging

from sys_func.read_config import load_yaml

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='monitor.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()


def get_consume_coupon_info():
    config_data = load_yaml('config_monitor.yaml')

    keyword = config_data.get('baidu').get('kw')
    # keyword = "消费券"

    kw = urllib.parse.quote(keyword)
    headers = {
        "cookie": "BAIDUID=7DAB7A615C3F61CE7778E4667B32C302:SL=0:NR=10:FG=1;",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"}
    # url = f"http://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word={kw}"
    url = f"https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd={kw}&medium=0"
    try:
        r = requests.get(url, headers=headers, timeout=10)

        soup = BeautifulSoup(r.text, 'html.parser')
        # print(soup.prettify())
        news = soup.find(id='content_left').find_all('div', class_='result-op')
        # print(news)
        # 取第一条结果
        first_new = news[0]
        # 题目
        news_title = first_new.find('a').text
        news_href = first_new.find('a').get('href')
        # 发布时间 与 新闻简述
        news_published_time, news_brief = [element.text for element in
                                           first_new.find_all('span', class_='c-font-normal')]
        # 新闻来源
        news_source = first_new.find('span', class_='c-color-gray').text

        return news_title, news_href, news_brief, news_published_time, news_source
    except Exception as e:
        logger.error(f"获取消费券信息报错，报错信息：{e}")
        # print(f"获取消费券信息报错，报错信息：{e}")
        return "获取消费券报错，请及时去处理", "https://no18.fun", "获取消费券报错", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "自动爬取程序"


if __name__ == '__main__':
    print(get_consume_coupon_info())
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
